<template>
	<view class="container">
		<view class="scan-btn">
			<text class="titles">网络设置</text>
			<uni-icons type="loop" size="26"  @click="startScan"></uni-icons>
		</view>
		
		<view class="wifi-list">
			<view class="wifi-item" v-for="wifi in wifiList" :key="wifi.SSID">
				<view class="wifi-content">
					<text class="wifi-name">{{wifi.SSID}}</text>
					<text class="wifi-signal">信号强度: {{wifi.signalStrength}}%</text>
				</view>
				<view class="wifi-buttons">
					<text class="btns1" @click="connectWifi(wifi)">{{wifi.connected ? '已连接' : '连接'}}</text>
				</view>
			</view>
		</view>
		
	
		
		<view style="text-align: center;margin-top: 100rpx; display:flex;gap:20rpx;justify-content: center;">
			<text class="btns" @click="saveNext">跳过</text><text class="btns" @click="saveWifi">保存并进入下一步</text>
		</view>
	</view>

	<uni-popup ref="inputDialog" type="dialog">
		<uni-popup-dialog ref="inputClose" mode="input" title="编辑线路名称" v-model="names" placeholder="请输入名称"
			@confirm="dialogInputConfirm"></uni-popup-dialog>
	</uni-popup>
	
	<uni-popup ref="passwordDialog" type="dialog">
		<uni-popup-dialog ref="passwordClose" mode="input" title="输入WiFi密码" v-model="wifiPassword" placeholder="请输入WiFi密码"
			@confirm="connectWithPassword"></uni-popup-dialog>
	</uni-popup>
</template>

<script setup>
	import {
		ref,onUnmounted,onMounted,
		watch
	} from 'vue';
	import {
		getDeviceLineList,setNetConfig
	} from "@/api/wuLian.js"
	import {
		onShow,
		onLoad
	} from "@dcloudio/uni-app"
	
	const wifiList = ref([])
	const scanning = ref(false)
	const wifiPassword = ref("")
	const currentWifi = ref(null)
	const savedWifiPasswords = ref({}) // 用于保存WiFi密码
	
	onMounted(()=>{
		startScan()
		setTimeout(()=>{
			startScan()
		},1000)
	})
	
	// 开始扫描WiFi
	function startScan() {
		if (scanning.value) return
		scanning.value = true
		wifiList.value = []
		
		// 先获取当前连接的WiFi
		wx.getConnectedWifi({
			success: (res) => {
				console.log('当前连接的WiFi:', res)
				res.wifi.password = savePasswordValues.value
				currentWifi.value = res.wifi
				// 继续扫描WiFi列表
				scanWifiList(res.wifi)
			},
			fail: () => {
				// 如果没有连接WiFi，直接扫描列表
				scanWifiList()
			}
		})
	}
	
	// 扫描WiFi列表
	function scanWifiList(currentWifi = null) {
		// 直接尝试初始化WiFi模块
		wx.startWifi({
			success: () => {
				// 初始化成功后获取WiFi列表
				wx.getWifiList({
					success: () => {
						// 监听WiFi列表更新
						wx.onGetWifiList((res) => {
							console.log(res,79)
							const wifiListData = res.wifiList.map(wifi => {
								// 检查是否是当前连接的WiFi
								const isConnected = currentWifi && 
									(wifi.SSID === currentWifi.SSID || wifi.BSSID === currentWifi.BSSID)
								return {
									SSID: wifi.SSID,
									signalStrength: wifi.signalStrength,
									connected: isConnected,
									BSSID: wifi.BSSID,
									password: isConnected ? savedWifiPasswords.value[wifi.SSID] : undefined
								}
							})
							console.log(wifiListData, 103)
							wifiList.value = wifiListData
							scanning.value = false
						})
					},
					fail: (err) => {
						console.error('获取WiFi列表失败:', err)
						uni.showToast({
							title: '获取WiFi列表失败，请检查WiFi是否开启',
							icon: 'none'
						})
						scanning.value = false
					}
				})
			},
			fail: (err) => {
				console.error('初始化WiFi模块失败:', err)
				// 在iOS上，即使WiFi已开启也可能返回失败，所以这里不直接提示错误
				// 而是尝试直接获取WiFi列表
				wx.getWifiList({
					success: () => {
						wx.onGetWifiList((res) => {
							const wifiListData = res.wifiList.map(wifi => {
								// 检查是否是当前连接的WiFi
								const isConnected = currentWifi && 
									(wifi.SSID === currentWifi.SSID || wifi.BSSID === currentWifi.BSSID)
								return {
									SSID: wifi.SSID,
									signalStrength: wifi.signalStrength,
									connected: isConnected,
									BSSID: wifi.BSSID,
									password: isConnected ? savedWifiPasswords.value[wifi.SSID] : undefined
								}
							})
							console.log(wifiListData, 103)
							wifiList.value = wifiListData
							scanning.value = false
						})
					},
					fail: (err) => {
						console.error('获取WiFi列表失败:', err)
						uni.showModal({
							title: '提示',
							content: '请确保已开启WiFi并授予小程序WiFi权限',
							showCancel: false
						})
						scanning.value = false
					}
				})
			}
		})
	}
	
	// 连接WiFi
	function connectWifi(wifi) {
		currentWifi.value = wifi
		if (wifi.connected) {
			// 如果已连接，显示密码
			uni.showModal({
				title: 'WiFi密码',
				content: `当前WiFi密码: ${wifi.password || '未保存'}`,
				showCancel: false
			})
			return
		}
		
		console.log(currentWifi.value, 168)
		
		// 弹出密码输入框
		passwordDialog.value.open()
	}
	const savePasswordValues = ref("")
	// 使用密码连接WiFi
	function connectWithPassword(password) {
		savePasswordValues.value = password
		if (!currentWifi.value) return
		
		// 保存密码
		savedWifiPasswords.value[currentWifi.value.SSID] = password
		
		wx.connectWifi({
			SSID: currentWifi.value.SSID,
			BSSID: currentWifi.value.BSSID,
			password: password,
			success: () => {
				// 监听WiFi连接成功
				wx.onWifiConnected((res) => {
					currentWifi.value.connected = true
					uni.showToast({
						title: '连接成功',
						icon: 'success'
					})
					wifiPassword.value = ""
					currentWifi.value = null
					// 重新扫描WiFi列表以更新状态
					startScan()
				})
			},
			fail: (err) => {
				console.error('连接失败:', err)
				uni.showToast({
					title: '连接失败',
					icon: 'none'
				})
				wifiPassword.value = ""
				currentWifi.value = null
			}
		})
	}
	const mac =ref("")
	onLoad((option) => {
		mac.value = option.mac
	})
	
	watch(currentWifi, (newVal) => {
		console.log(newVal, 170)
	})		
	function saveNext(){
		uni.redirectTo({
			url: "/dianXiang/pages/xianLu?mac="+mac.value
		})
	}
	function saveWifi(){
		console.log(currentWifi.value,237)
		let params = {
			mac:mac.value,
			value3:currentWifi.value.SSID,
			value5:currentWifi.value.password
		}
		if(currentWifi.value.password){
			setNetConfig(params).then(e=>{
				console.log(e,248)
				uni.redirectTo({
					url: "/dianXiang/pages/xianLu?mac="+mac.value
				})
			})
		}else{
			uni.showToast({
				title: '为获取到WiFi密码',
				icon: 'none'
			})
			uni.redirectTo({
				url:"/wuLian/pages/index"
			})
		}
		// console.log(params,248)
		// uni.redirectTo({
		// 	url:"/wuLian/pages/index"
		// })
	}
	const inputDialog = ref()
	const passwordDialog = ref()
	const lineArr = ref([])
	const names = ref("")
	const currtion = ref({})

	function bianJi(item) {
		console.log(item, 43)
		names.value = item.title
		currtion.value = item
		inputDialog.value.open()
	}

	function dialogInputConfirm(e) {
		currtion.value.title = e
		currtion.value = {}
		names.value = ""
	}
	
	// 页面卸载时清理WiFi监听
	onUnmounted(() => {
		wx.stopWifi()
	})
</script>

<style scoped>
	.container {
		height: 100vh;
		background-color: rgba(250, 250, 250, 1);
		padding: 20rpx;
	}
	
	.scan-btn {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}
	
	.wifi-list {
		margin-bottom: 30rpx;
	}
	
	.wifi-item {
		height: 140rpx;
		margin: 10rpx 0;
		border: 2rpx solid #e0e0e0;
		border-radius: 10rpx;
		display: flex;
		background-color: #fff;
		padding: 0 20rpx;
	}
	
	.wifi-content {
		flex: 1;
		padding: 15rpx;
		display: flex;
		flex-direction: column;
	}
	
	.wifi-name {
		font-size: 32rpx;
		color: #333;
		margin-bottom: 8rpx;
	}
	
	.wifi-signal {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 15rpx;
	}
	
	.wifi-buttons {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.line-item {
		height: 140rpx;
		margin: 10rpx 0;
		border: 2rpx solid #e0e0e0;
		border-radius: 10rpx;
		display: flex;
		background-color: #fff;
		padding: 0 20rpx;
	}

	.line-content {
		flex: 1;
		padding: 15rpx;
		display: flex;
		flex-direction: column;
	}

	.line-title {
		font-size: 32rpx;
		color: #333;
		margin-bottom: 8rpx;
	}

	.line-id {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 15rpx;
	}

	.line-buttons {
		display: flex;
		gap: 20rpx;
		justify-content: center;
		align-items: center;
	}

	.btns1 {
		background-color: #E60012;
		border-radius: 10rpx;
		color: #fff;
		padding: 5rpx 10rpx;
		height: 50rpx;
	}

	.btns {
		background-color: #E60012;
		color: #fff;
		padding: 20rpx 40rpx;
		font-size: 26rpx;
		border-radius: 10rpx;
	}
</style>